package br.com.ir.tcc.geco.web;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;

public class WebUtils {
	
	public static Map<String, Object> toMap(Object bean, String... properties) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
		
		Map<String,Object> rootMap = new HashMap<String, Object>();
		
		for (int i = 0; i < properties.length; i++){
			
			String property = properties[i];
			
			if(property.contains(".")){ // NestedProperty 
				
				String[] nestedProperties = property.split("\\.");
				
				Map<String, Object> currentMap = rootMap;
				for (int j = 0; j < nestedProperties.length - 1; j++) {
					Map<String, Object> map = (Map<String, Object>) currentMap.get(nestedProperties[j]);
					if(map == null){
						map = new HashMap<String, Object>();
						currentMap.put(nestedProperties[j], map);
					}
					currentMap = map;
				}
				
				currentMap.put(nestedProperties[nestedProperties.length-1], PropertyUtils.getProperty(bean, property));
				
			} else {
				rootMap.put(property, PropertyUtils.getProperty(bean, property));
			}
			
		}
		
		return rootMap;
		
	}

}
